package com.wswy.wzcx.api;

import android.text.TextUtils;
import android.util.Log;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;

import java.io.IOException;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartBody.Part;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.ByteString;
import okio.Okio;
import okio.Source;

/**
 * Created by wangduheng26 on 2018/1/19.
 * wangduheng26@gmail.com
 */

class ParamInterceptor implements Interceptor {

    private static final String TAG = "ParamInterceptor";

    private static final MediaType CONTENT_TYPE =
            MediaType.parse("application/json; charset=utf-8");

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
//        Request request = beforeProcess(chain);
//        Response proceed = chain.proceed(request);
//        return afterProcess(proceed);
        Request request = chain.request();
        RequestBody body = request.body();

        if (body instanceof FormBody){
            FormBody formBody = (FormBody) body;

            FormBody.Builder builder = new Builder();

            int size = formBody.size();

            TreeMap<String,String> map = new TreeMap<>();
            for (int i = 0; i < size; i++) {
                String name = formBody.name(i);
                String value = formBody.value(i);
                map.put(name, value);

                builder.add(name,value);
            }

            if (!map.containsKey("sign")){
                String sign = ScUtil.ucSign(map);
                builder.add("sign",sign);
                return chain.proceed(request.newBuilder().method(request.method(),builder.build()).build());
            }

        }
        return chain.proceed(request);
    }
}
